<template>
  <div>
    <el-row >
      <el-col :span="2" :offset="4">
        <span>底图地址</span>
      </el-col>
      <el-col :span="10">
        <el-input v-model="originalUrl" placeholder="请输入底图地址" >{{originalUrl}}</el-input>
      </el-col>
      <el-col :span="4">
        <el-button @click="drawBackImg">绘制底图</el-button>
      </el-col>
    </el-row>
    <el-row>
      <img  crossOrigin="anonymous" :src="url" alt="">
    </el-row>
    <dialog-form ref="dialog" :form="form" :showDialog.sync="showDialog" v-on:close="showDialog = false" v-on:submit="closeDialog"></dialog-form>
    <el-row v-show="url.length > 0">
      <el-button v-on:click="addImg" >添加图片</el-button>
<!--      <el-button v-on:click="addText" >添加文字</el-button>-->
<!--      <el-button v-on:click="addWater" >添加水印</el-button>-->
      <el-button v-on:click="clear" >清空</el-button>
      <el-button v-on:click="importImg" >导出</el-button>
    </el-row>
    <p>{{qiniuUrl}}</p>
  </div>
</template>

<script>
  import DialogForm from './Learn/Form'
  import { MCanvas } from 'mcanvas'
  import loadEvents from '../Utils/Loading'
  // import {utils} from '../Utils/Utils'
  import md5 from 'js-md5';
  let Base64 = require('js-base64').Base64;
  // 创建画布，初始化 canvas；
  let mc = new MCanvas({
    width: 500,
    height: 500,
    backgroundColor: 'black',
  })
  let loading = new loadEvents();
  export default {
    name: 'ImageMerge',
    data(){
      return{
        url:'',
        originalUrl:'',
        token:'',
        qiniuaddr: "https://supimage.miniprogramhacker.cn", // 七牛云的图片外链地址
        domain: "https://upload-z2.qiniup.com", // 七牛云的上传地址（华南区）
        qiniuUrl:'',
        form: {
          imgUrl:'',
          imgWidth:'100%',
          xLocation:'center',
          yLocation:'center',
          scale:'1'
        },
        showDialog:false
      }
    },
    components:{
      DialogForm
    },
    mounted: function () {
      this.getQiniuToken();
    },
    methods:{
      // 绘制底图
      drawBackImg(){
        if (this.originalUrl.indexOf("http") != 0){
          this.$message({
            type:'info',
            message:'图片地址错误'
          });
          return;
        }
        mc.clear()
        mc.background(this.originalUrl, {
          left: 0,
          top: 0,
          color: '#000000',
          type: 'origin',
        })
        this.drawCanvas()
      },
      // 关闭弹窗，添加图片
      closeDialog(){
        this.showDialog = false
        var scr3 = 'https://supimage.miniprogramhacker.cn/beauty/faceWash/GiorgioArmanishsrdzcg_3.jpeg'
        var src = this.form.imgUrl + "?timeStamp=" + new Date().getTime();
        if (src.indexOf("http") != 0){
          this.$message({
            type:'info',
            message:'图片地址不是网络地址'
          });
          return;
        }
        // add 添加图片素材基础函数；
        mc.add(src, {
          width: this.form.imgWidth,
          pos: {
            x: this.form.xLocation,
            y: this.form.yLocation,
            scale: this.form.scale,
            rotate: 0,
          },
        })
        this.drawCanvas()
      },
      // 合成图片
      drawCanvas(){
        loading.open()
        mc.draw(b64 => {
          this.url = b64
          loading.close()
        }).catch(error => {
          loading.close()
          this.$message(
            {
              type:'info',
              message:'图片合成失败'
            }
          )
        })
      },
      addImg(){
        this.showDialog = true
      },
      // 清空图片
      clear(){
        mc.clear()
        this.drawBackImg();
      },
      // 导出图片
      importImg(){
        loading.open()
        var file = this.dataURLToFile(this.url)
        this.uploadImgToQiniu(file)
      },
      //上传图片到七牛
      uploadImgToQiniu(file){
        let randText = this.randomText(5)
        let timestamp = new Date().getTime()
        let baseN = Base64.encode(this.randomText(9))
        let mdName = md5(baseN+timestamp+randText)
        let key = 'testPic/'+mdName

        const axiosInstance = this.$axios.create({withCredentials: false});    //withCredentials 禁止携带cookie，带cookie在七牛上有可能出现跨域问题
        let data = new FormData();
        data.append('token', this.token);     //七牛需要的token，叫后台给，是七牛账号密码等组成的hash
        data.append('file', file);
        data.append('key', key)

        axiosInstance({
          method: 'POST',
          url: this.domain,  //上传地址
          data: data,
          timeout:30000,      //超时时间，因为图片上传有可能需要很久
        }).then(data =>{
          this.qiniuUrl = this.qiniuaddr+ "/"+key
          loading.close()
          this.$message(
            {
              type:'success',
              message:'上传成功'
            }
          )
        }).catch(function(err) {

          loading.close()
          this.$message(
            {
              type:'info',
              message:'上传失败'
            }
          )
        });
      },
      //请求后台拿七牛云token
      getQiniuToken() {
        this.getAxios('public/qiniuToken').then(res => {
          this.token = res.data;
        });
      }

    }
  }
</script>

<style scoped>
  img { max-width: 20%; height: auto; width: auto; width: auto; }
  .el-row {
    margin-bottom: 20px;
  &:last-child {
     margin-bottom: 0;
   }
  }
</style>
